<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addBtn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
        v-if="this.arr.length > 0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val, index) in arr" :key="index">
          <td>{{ val.id }}</td>
          <td>{{ val.name }}</td>
          <td>{{ val.age }}</td>
          <td>{{ val.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="upd(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, name: "tom", age: 19, sex: "女" },
        { id: 2, name: "jerry", age: 20, sex: "男" },
      ],
      name: "",
      age: 0,
      sex: "男",
      editIndex: null,
    };
  },
  methods: {
    addBtn() {
      // 添加/修改-点击事件方法
      let newObj = {
        id: this.editIndex + 1,
        name: this.name,
        age: this.age,
        sex: this.sex,
      };
      if (this.editIndex !== null) {
        this.$set(this.arr, this.editIndex, newObj);
        this.editIndex = null;
      } else {
        let index = this.arr.length - 1;
        let newMoban = {
          id: index + 2,
          name: this.name,
          age: this.age,
          sex: this.sex,
        };
        this.arr.push(newMoban);
      }
    },
    del(i) {
      this.arr.splice(i, 1);
    },
    upd(i) {
      let newObj = this.arr[i];
      this.name = newObj.name;
      this.age = newObj.age;
      this.sex = newObj.sex;
      this.editIndex = i;
    },
  },
};
</script>
